package com.etlmaster.executor.steps.web;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.utils.LogWriter;
import com.etlmaster.executor.utils.StepState;
import com.sun.jersey.spi.container.servlet.ServletContainer;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
@StepInstruction("restprovider")

public class RestFulServiceProviderStep extends Step{

	private RestFulServiceProviderStepMeta meta;
	private static Server server;
	public RestFulServiceProviderStep(StepMeta meta) {
		super(meta);
		this.meta=(RestFulServiceProviderStepMeta) meta;
	}

	@Override
	protected int handle() {
		try {
			if(getServer()==null||!getServer().isStarted())
			{
				start(meta.getPort());
				meta.log("INFO","服务启动，端口为:{}！",meta.getPort()+"");
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogWriter.addLog("ERROR",e.getMessage());
			return StepState.RUNNING_FAILED;

		}
		return StepState.RUNNING_SUCCESSED;
	}

	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}
	private void start(int port) throws Exception {  
        server=new Server(port);  
        ServletContextHandler context = new ServletContextHandler(  
                ServletContextHandler.SESSIONS);  
        context.setContextPath("/");  
        getServer().setHandler(context);  
        ServletHolder sh = new ServletHolder(ServletContainer.class);  
        sh.setInitParameter(  
                "com.sun.jersey.config.property.resourceConfigClass",  
                "com.sun.jersey.api.core.PackagesResourceConfig");  
        sh.setInitParameter("com.sun.jersey.config.property.packages",  
                meta.getPkg());  
        context.addServlet(sh, "/*");  
        getServer().start();  
        
    }

	public static Server getServer() {
		return server;
	}

}
